//
//  JPUserInfoModel.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 16/9/22.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit

private let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archiver")

class JPUserInfoModel: NSObject,NSCoding {

    //用户授权唯一票据
    var access_token: String?
    //授权的到期日期
    var expiresDate: Date?
    //access_token的生命周期，单位是秒数
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date().addingTimeInterval(expires_in)
        }
    }
    //用户头像地址
    var avatar_large: String?
    //用户昵称
    var name: String?
    //用户id
    var uid: Int64 = 0
    
    
    //KVC构造方法
    init(dict:[String: Any]) {
        super.init()
        
        setValuesForKeys(dict);
    }
    
    //防止报错
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    func encode(with aCoder: NSCoder) {
        
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        name = aDecoder.decodeObject(forKey: "name") as? String
        uid = aDecoder.decodeInt64(forKey: "uid")
    }
    
    func encodeUserInfo() {
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    class func decodeUserInfo() -> JPUserInfoModel? {
        
        return (NSKeyedUnarchiver.unarchiveObject(withFile: path) as? JPUserInfoModel)
    }
}

    








